package top.cyuw.subjectsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import top.cyuw.subjectsystem.dto.PagingParamDto;
import top.cyuw.subjectsystem.dto.depart.DepartCreateRequest;
import top.cyuw.subjectsystem.dto.depart.DepartEditRequest;
import top.cyuw.subjectsystem.entity.Depart;
import top.cyuw.subjectsystem.mapper.DepartMapper;
import top.cyuw.subjectsystem.service.DepartService;
import top.cyuw.subjectsystem.util.MapperUtils;
import top.cyuw.subjectsystem.vo.PagingVo;
import top.cyuw.subjectsystem.vo.depart.DepartVo;

import java.util.Date;
import java.util.List;

@Service
public class DepartServiceImpl extends ServiceImpl<DepartMapper, Depart> implements DepartService {

    @Override
    public Boolean create(DepartCreateRequest request) {
        Depart depart = new Depart();
        depart.setName(request.getName());
        Date now = new Date();
        depart.setUpdateTime(now);
        depart.setCreateTime(now);
        return super.save(depart);
    }

    @Override
    public Boolean delete(Integer id) {
        return super.removeById(id);
    }

    @Override
    public Boolean edit(DepartEditRequest request) {
        LambdaUpdateWrapper<Depart> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Depart::getId, request.getId());
        if (StringUtils.isNotEmpty(request.getName())) {
            wrapper.set(Depart::getName, request.getName());
        }
        if (StringUtils.isNotEmpty(request.getName())) {
            wrapper.set(Depart::getName, request.getName());
        }
        wrapper.set(Depart::getUpdateTime, new Date());
        return super.update(wrapper);
    }

    @Override
    public PagingVo<DepartVo> search(PagingParamDto<String> request) {
        LambdaQueryWrapper<Depart> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Depart::getName, request.getParam());
        Page<Depart> page = super.page(
                new Page<>(request.getPageNum(), request.getPageSize()), wrapper);
        return PagingVo.of(MapperUtils.mapList(page.getRecords(), DepartVo.class),
                page.getTotal(), page.getCurrent(), page.getPages());
    }

    @Override
    public List<DepartVo> all() {
        return MapperUtils.mapList(super.list(), DepartVo.class);
    }

}
